package com.cloud.manager.core.component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 描述：属性名去填充数据
 *
 * @author FineEx   2021/11/18
 * @version 1.0
 */
@Component
public class TimeHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        setIfAbsent("createTime", LocalDateTime.now(), metaObject);
        setIfAbsent("updateTime", LocalDateTime.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setIfAbsent("updateTime", LocalDateTime.now(), metaObject);
    }

    private void setIfAbsent(String fieldName, Object value, MetaObject metaObject) {
        if (getFieldValByName(fieldName, metaObject) != null) {
            return;
        }
        setFieldValByName(fieldName, value, metaObject);
    }
}
